<template>
  <div class="app-container">
    <el-form ref="form" :model="form" label-width="70px">
      <el-row :gutter="24">
        <el-col :span="4">
          <el-form-item label="用户名称" prop="username">
            <el-input v-model="form.username" placeholder="请输入用户名称" />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="用户姓名" prop="name">
            <el-input v-model="form.name" placeholder="请输入用户名称" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="用户状态" prop="name">
            <el-select v-model="form.state" placeholder="请选择">
              <el-option label="请选择" value="" />
              <el-option label="启用" value="1" />
              <el-option label="禁用" value="2" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="loadData">搜索</el-button>
          <el-button @click="searchResetForm('form')">重 置</el-button>

        </el-col>
      </el-row>
    </el-form>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="primary" v-permission="['sys:user:add']" @click="add" size="small">添加</el-button>
        <el-button type="danger" v-permission="['sys:user:delete']" @click="batchDelete" size="small">删除</el-button>
      </template>
      <el-table
        v-loading="loading"
        :data="tableData"

        @selection-change="selectionChange"
      >
        <el-table-column
          type="selection"
          align="center"
          :selectable="checkSelectTable"
        />
        <el-table-column
          label="序号"
          type="index"
          align="center"
          width="50"
        />
        <el-table-column v-for="(item,index) in columnLists"  :key="index" :prop="item.prop" :label="item.label" align="center" />
        <el-table-column
          fixed="right"
          label="操作"
          width="200"
          align="center"
        >
          <template slot-scope="scope">
            <el-button
              class="deleted"
              type="text"
              size="mini"
              @click="del(scope.$index)"
              v-permission="['sys:user:delete']"
            >
              删除
            </el-button>

            <el-button
              type="text"
              size="mini"
              @click="edit(scope.$index)"
              v-permission="['sys:user:edit']"
            >
              编辑
            </el-button>

            <el-button  v-permission="['sys:user:change:state']"  type="text" size="mini"  @click="changeState(scope.$index)">
              更改状态
            </el-button>
            <el-button  v-permission="['sys:user:reset']"  type="text" size="mini" @click="resetPsd(scope.$index)">
              重置密码
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination :total="total" :current-page="pageNum" :page-size="pageSize" @handleChange="handleChange" />
    </el-card>
    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="dialogVisible" width="45%">
      <el-form ref="formLabelAlign" :model="formLabelAlign" :rules="rules" label-width="140px">
        <el-row>
          <el-col :span="10">
            <el-form-item label="账号名称" prop="username">
              <el-input v-model="formLabelAlign.username" clearable :disabled="disabled" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="用户姓名" prop="name">
              <el-input v-model="formLabelAlign.name" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="用户状态" prop="state">
              <el-select v-model="formLabelAlign.state" clearable style="width: 100%;" placeholder="请选择">
                <el-option label="请选择" value="" />
                <el-option label="启用" value="0" />
                <el-option label="禁用" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="用户角色" prop="roleIds">
              <el-select v-model="formLabelAlign.roleIds" style="width: 100%;" multiple placeholder="请选择">
                <el-option
                  v-for="item in roleLists"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          <el-col :span="10">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="formLabelAlign.phone" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model="formLabelAlign.email" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="用户性别" prop="state">
              <el-select v-model="formLabelAlign.sex" clearable style="width: 100%;" placeholder="请选择">
                <el-option label="请选择" value="" />
                <el-option label="男" value="0" />
                <el-option label="女" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="10">
            <el-form-item label="用户头像" prop="phone">
              <el-upload
                :action="action"
                class="avatar-uploader"
                :headers="headers"
                :show-file-list="false"
                accept="image/png, image/jpeg,.pdf"
                :on-success="handleAvatarSuccess">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col> -->

        </el-row>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="save('formLabelAlign')">确 定</el-button>
        <el-button size="mini" @click="resetForm('formLabelAlign')">重 置</el-button>
        <el-button size="mini" type="danger" @click="cancel('formLabelAlign')">关 闭</el-button>
      </div>
    </el-dialog>
    <el-dialog title="重置密码" :close-on-click-modal="false" :visible.sync="dialogReset" width="25%">
      <el-form ref="formLabelReset" :model="formLabelReset" :rules="resetRules" >
        <el-row>
          <el-col :span="24">
            <el-form-item     prop="password">
              <el-input v-model="formLabelReset.password" placeholder="请输入密码" type="password" show-password clearable   />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="saveResetPsd('formLabelReset')">确 定</el-button>
        <el-button size="mini" @click="resetForm('formLabelReset')">重 置</el-button>
        <el-button size="mini" type="danger" @click="cancelResetPsd('formLabelReset')">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import {
  getUserLists,
  del,
  findUserById,
  saveUser,
  getRoleLists,
  changeUser,
  deleteUser
} from '@/api/user'
import { showData, deleteData, resetForm, validate, success, fail } from '@/api/common'
import Pagination from '@/components/Pagination'
import { getToken } from '@/utils/auth'
import permission from '@/directive/permission/index.js'
import checkPermission from '@/directive/permission/permission'
export default {
  name: 'PagePermission',
  components: {
    Pagination
  },
  directives: { permission },
  data() {
    return {
      dialogReset:false,
      headers:{
        Authorization:getToken()
      },
      action:process.env.VUE_APP_BASE_API+'upload/image',
      pageNum: 1, pageSize: 10, total: 0,
      form: { username: '', name: '', state: '', deptId: '' },
      tableData: [],
      selectRows: [],
      dialogVisible: false,
      title: '添加用户',
      columnLists: [
        { prop: 'username', label: '账号名称' },
        { prop: 'name', label: '用户姓名' },
        { prop: 'sex', label: '用户性别' },
        { prop: 'roleName', label: '角色名称' },
        { prop: 'phone', label: '手机号码' },
        { prop: 'email', label: '电子邮箱' },
        { prop: 'state', label: '用户状态' },
        { prop: 'createTime', label: '创建时间' }
      ],
      type: 'user',
      rules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'change' }

        ],
        name: [
          { required: true, message: '请输入用户姓名', trigger: 'change' }
        ],
        state: [
          { required: true, message: '请选择用户状态', trigger: 'change' }
        ],
        sex: [
          { required: true, message: '请选择用户性别', trigger: 'change' }
        ],
        roleIds: [
          { required: true, message: '请选择用户角色', trigger: 'change' }
        ]
      },
      passwordType: 'password',
      formLabelAlign: {
        username: '',
        name: '',
        email: '',
        phone: '',
        state: '',
        id: '',
        sex: '',
        roleIds: []
      },
      formLabelReset: { password: '' },
      resetRules: {
        password: [
          { required: true, message: '请输入用户密码', trigger: 'change' }
        ]
      },
      imageUrl: '',
      disabled: false,
      userState: '',
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      roleLists: [],
      loading: true

    }
  },
  created() {

  },
  mounted() {
    this.loadData()
    this.loadRoleLists()
  },
  methods: {

    checkPermission,
    saveResetPsd(formName) {
      if (validate(this, formName)) {

      }
    },
    cancelResetPsd(formName) {
      this.dialogReset= false
    },
    resetPsd(index) {
      this.dialogReset=true
    },
    loadRoleLists() {
      getRoleLists().then(res => {
        if (res.code === 200) {
          this.roleLists = res.data
        }
      })
    },
    checkSelectTable(row) {
      if (row.username==='admin') {
        return false
      } else {
        return true
      }
    },
    del(index) {
      this.$confirm('此操作将永久删除该用户信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(this.tableData[index].id).then(response => {
          if (response.code === 200) {
            success(response.msg)
            this.loadData()
          } else {
            fail(response.msg)
          }
        })
      }).catch(() => {

      })
    },

    batchDelete(){
     if(this.selectRows.length===0){
       fail('请选择删除的数据')
       return false
     }
    },
    edit(index) {
      this.title = '编辑用户信息'
      this.disabled = true
      const row = this.tableData[index]

      findUserById(row.id).then(response => {
        if (response.code === 200) {
          this.formLabelAlign = JSON.parse(JSON.stringify(response.data))
        }
        this.dialogVisible = true
      })
    },
    cancel(formName) {
      resetForm(this, formName)
      this.dialogVisible = false
    },
    changeState(index) {
      const id = this.tableData[index].id
      this.$confirm('确认修改当前用户的状态, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        changeUser(id).then(res => {
          if (res.code === 200) {
            success(res.msg)
            this.loadData()
          } else {
            fail(res.msg)
          }
        })
      }).catch(() => {

      })
    },
    resetForm(formName) {
      resetForm(this, formName)
    },
    searchResetForm(formName) {
      resetForm(this, formName)
      this.loadData()
    },
    save(formName) {
      if (validate(this, formName)) {
        saveUser(this.formLabelAlign).then(response => {
          if (response.code === 200) {
            success(response.msg)
            this.dialogVisible = false
            this.loadData()
          } else {
            fail(response.msg)
          }
        })
      }
    },
    add(formName) {
      this.disabled=false
      this.title = '添加用户信息'
      this.$nextTick(()=>{
        resetForm(this,formName)
      })
      this.dialogVisible = true


    },
    deleteUser() {
      if (deleteData(this.selectRows)) {
        const array = []
        this.selectRows.forEach(row => {
          array.push(row.id)
        })
        deleteUser(array).then(response => {
          console.log('response', response)
        })
      }
    },
    selectionChange(rows) {
      this.selectRows = rows
    },
    selectable(row, rowIndex) {
      if (row.username === 'admin') {
        return false
      } else {
        return true
      }
    },
    handleChange(pageNum, pageSize) {
      this.pageNum = pageNum
      this.pageSize = pageSize
      this.loadData()
    },

    loadData() {
      this.form.pageNum = this.pageNum
      this.form.pageSize = this.pageSize
      getUserLists(this.form).then(response => {

        showData(response, this)
      })
    },
    handleRolesChange() {
      this.$router.push({ path: '/system/index?' + +new Date() })
    }
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 140px;
  height: 140px;
  line-height: 140px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader img{
  cursor: pointer;
  width: 100px;
  border-radius: 50px;
  height: 100px;
}
.deleted{
  color: #F56C6C;
}

</style>
